<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodsList" :key="good.id">
        <GoodsItem :good="good" />
      </li>
    </ul>

    <xtx-infinite-load
      :isLoading="isLoading"
      :isFinished="isFinished"
      @load="loadNextPage"
    ></xtx-infinite-load>
  </div>
</template>

<script>
import { ref, inject, watch } from 'vue'
import { useRoute } from 'vue-router'
import { findSubCategoryGoods } from '@/api/category'
import GoodsItem from './GoodItem.vue'
export default {
  components: {
    GoodsItem
  },
  setup () {
    const isLoading = ref(false)
    const isFinished = ref(false)

    const goodsList = ref([])
    const route = useRoute()

    // 默认请求参数就是普通js对象，不是响应式
    const paramsGoodsList = {
      page: 0, // 默认页码也得修改为零
      pageSize: 20,
      categoryId: route.params.id,
      // 自己选择的筛选条件
      sortField: null, // 排序类别
      attrs: [], // 商品属性
      brandId: null // 品牌名称
    }

    const filterParams = inject('filterParams')
    // 监听filterParams筛选条件数据的变化
    watch(
      () => filterParams.value,
      (newVal) => {
        // 数据变化后合并参数
        // 重新发送请求
        // const newParamsGoodsList = { ...paramsGoodsList, ...newVal }
        // getGoodsList(newParamsGoodsList)

        // 如果这里修改goodsList.value=[]，onMounted，watch都不再需要发送请求，只要loadNextPage发请求
        // 因为goodsList.value=[]时，ul高度为零，可以检测到xtx-infinite-load组件里的DOM
        // 只需要修改参数即可
        goodsList.value = []
        paramsGoodsList.page = 0
        isFinished.value = false
      },
      {
        deep: true // 深度监听
      }
    )

    // const getGoodsList = async (params) => {
    //   const { result } = await findSubCategoryGoods(params)
    //   goodsList.value = result.items
    // }

    const loadNextPage = async () => {
      /**
       * 1.修改正在加载为true,且页码+1
       * 2.发请求
       * 3.请求完毕修改正在加载为false
       * 4.判断是否还有数据需要请求，若没有，修改加载完毕为true
       */
      isLoading.value = true
      paramsGoodsList.page++

      const { result } = await findSubCategoryGoods(
        {
          ...paramsGoodsList,
          ...filterParams
        }
      )
      goodsList.value.push(...result.items)

      isLoading.value = false

      if (goodsList.value.length === result.counts) {
        isFinished.value = true
      }
    }

    // onMounted(() => {
    //   getGoodsList(paramsGoodsList)
    // })

    return { goodsList, isLoading, isFinished, loadNextPage }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
